package com.flyco.modules.sms.service.impl;

import com.flyco.modules.sms.entity.SmsLotteryInfo;
import com.flyco.modules.sms.entity.SmsLotteryItem;
import com.flyco.modules.sms.entity.SmsLotteryHistory;
import com.flyco.modules.sms.mapper.SmsLotteryItemMapper;
import com.flyco.modules.sms.mapper.SmsLotteryHistoryMapper;
import com.flyco.modules.sms.mapper.SmsLotteryInfoMapper;
import com.flyco.modules.sms.service.ISmsLotteryInfoService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 抽奖
 * @Author: flyco
 * @Date:   2020-04-16
 * @Version: V1.0
 */
@Service
public class SmsLotteryInfoServiceImpl extends ServiceImpl<SmsLotteryInfoMapper, SmsLotteryInfo> implements ISmsLotteryInfoService {

	@Autowired
	private SmsLotteryInfoMapper smsLotteryInfoMapper;
	@Autowired
	private SmsLotteryItemMapper smsLotteryItemMapper;
	@Autowired
	private SmsLotteryHistoryMapper smsLotteryHistoryMapper;
	
	@Override
	@Transactional
	public void saveMain(SmsLotteryInfo smsLotteryInfo, List<SmsLotteryItem> smsLotteryItemList,List<SmsLotteryHistory> smsLotteryHistoryList) {
		smsLotteryInfoMapper.insert(smsLotteryInfo);
		for(SmsLotteryItem entity:smsLotteryItemList) {
			//外键设置
			entity.setLotteryId(smsLotteryInfo.getId());
			smsLotteryItemMapper.insert(entity);
		}
		for(SmsLotteryHistory entity:smsLotteryHistoryList) {
			//外键设置
			entity.setLotteryId(smsLotteryInfo.getId());
			smsLotteryHistoryMapper.insert(entity);
		}
	}

	@Override
	@Transactional
	public void updateMain(SmsLotteryInfo smsLotteryInfo,List<SmsLotteryItem> smsLotteryItemList,List<SmsLotteryHistory> smsLotteryHistoryList) {
		smsLotteryInfoMapper.updateById(smsLotteryInfo);
		
		//1.先删除子表数据
		smsLotteryItemMapper.deleteByMainId(smsLotteryInfo.getId());
		smsLotteryHistoryMapper.deleteByMainId(smsLotteryInfo.getId());
		
		//2.子表数据重新插入
		for(SmsLotteryItem entity:smsLotteryItemList) {
			//外键设置
			entity.setLotteryId(smsLotteryInfo.getId());
			smsLotteryItemMapper.insert(entity);
		}
		for(SmsLotteryHistory entity:smsLotteryHistoryList) {
			//外键设置
			entity.setLotteryId(smsLotteryInfo.getId());
			smsLotteryHistoryMapper.insert(entity);
		}
	}

	@Override
	@Transactional
	public void delMain(Long id) {
		smsLotteryItemMapper.deleteByMainId(id);
		smsLotteryHistoryMapper.deleteByMainId(id);
		smsLotteryInfoMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			smsLotteryItemMapper.deleteByMainId(Long.valueOf(id.toString()));
			smsLotteryHistoryMapper.deleteByMainId(Long.valueOf(id.toString()));
			smsLotteryInfoMapper.deleteById(id);
		}
	}
	
}
